using SDL;

class Window : Object {
	public Rectangle size { get; protected set; }
	public string text { get; protected set; }
	public signal void on_key_down(KeyboardEvent event);
	public signal void on_key_up(KeyboardEvent event);

	public World world { get; set; }

	private bool running = false;
	private unowned Screen screen;

	public Window(Rectangle size, string text = "Window") {
		this.size = size;
		this.text = text;
	}

	public void show(World world) {
		if (!this.running) {
			this.video_init();
			// You would want to show menu and all that stuff but this is enough for now
			this.world = world;
			this.running = true;
			while (this.running) {
				this.handle_events();
				world.render(this.screen);
				this.screen.flip();
				stderr.flush();
			}
		}
	}

	private void video_init() {
		uint32 flags = SurfaceFlag.DOUBLEBUF | SurfaceFlag.HWACCEL | SurfaceFlag.HWSURFACE;
		this.screen = Screen.set_video_mode(this.size.width, this.size.height, 32, flags);
		if (this.screen == null) {
			stderr.printf("Cannot initialize video");
		}
		WindowManager.set_caption(this.text, "");
	}

	private void handle_events() {
		Event event = Event();
		while (Event.poll(event) == 1) {
			switch (event.type) {
				case EventType.QUIT:
					this.running = false;
					break;
				case EventType.KEYDOWN:
					this.on_key_down(event.key);
					break;
				case EventType.KEYUP:
					this.on_key_up(event.key);
					break;
			}
		}
	}

}

